<script setup lang="ts">
import {
  trademarkPage,
  trademarkDel,
  trademarkSaveOrUpdate,
  trademarkDetail,
} from "@/api/product/trademark";
import type { TrademarkData } from "@/api/product/trademark/type";
import type { BasePageReq, BasePageResp } from "@/api/baseType";
import type { UploadProps } from "element-plus";
import { ref, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
//表格数据
const tableData = ref<TrademarkData[]>([]);
//分页参数
const pageReq = ref<BasePageReq>({ page: 1, limit: 10 });
//分页器参数
const paginationParam = ref<BasePageResp>({
  total: 0,
  size: 0,
  current: 0,
  searchCount: false,
  pages: 0,
});
//控制对话框显示参数
const dialogVisible = ref(false);
//对话框数据
let dialogData = ref<TrademarkData>({ id: undefined, tmName: "", logoUrl: "" });
//获取el-form组件实例
const dialogForm = ref();
onMounted(() => {
  pageQuery();
});
//分页查询
const pageQuery = () => {
  trademarkPage(pageReq.value).then((res) => {
    tableData.value = res.data.records;
    //解构res.data
    const { total, size, current, searchCount, pages } = res.data;
    //将解构后的数据赋值给分页器
    paginationParam.value = { total, size, current, searchCount, pages };
  });
};
//页码变更时
const handleCurrentChange = (current: number) => {
  pageReq.value.page = current;
  pageQuery();
};
//页数变更时
const handleSizeChange = (size: number) => {
  pageReq.value.limit = size;
  pageReq.value.page = 1;
  pageQuery();
};
//删除品牌
const deleteTrademark = async (id: number) => {
  let res = await trademarkDel(id);
  if (res.code === 200) {
    if (tableData.value.length <= 1) pageReq.value.page -= 1;
    pageQuery();
  } else {
    ElMessage.error(res.message);
  }
};
//删除品牌
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定删除序号为" + `${id}` + "的品牌")
    .then(() => {
      deleteTrademark(id);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};
//编辑品牌
const handleEdit = async (id: number) => {
  resetDialogData();
  await trademarkDetail(id).then((res) => {
    dialogData.value.tmName = res.data.tmName;
    dialogData.value.id = res.data.id;
    dialogData.value.logoUrl = res.data.logoUrl;
  });
  dialogVisible.value = true;
};
//添加品牌
const openDialog = () => {
  dialogVisible.value = true;
  resetDialogData();
};
//初始化弹窗数据
const resetDialogData = () => {
  dialogData.value = {
    id: undefined,
    logoUrl: "",
    tmName: "",
  };
  dialogForm.value?.clearValidate();
};
//关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  dialogData.value.logoUrl = response.data;
  //清除表单验证
  dialogForm.value.clearValidate("logoUrl");
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  //图片类型判断，只能传jpg、jpeg、gif、png类型
  const allowType = ["jpg", "jpeg", "png", "gif"];
  if (!allowType.includes(rawFile.type.split("/")[1])) {
    ElMessage.error("只能传jpg、jpeg、gif、png类型的图片");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
//保存数据
const saveDialogData = async () => {
  //触发表单校验 await 等待校验完成，执行失败后续不执行
  await dialogForm.value?.validate();
  let res: any = await trademarkSaveOrUpdate(dialogData.value);
  if (res.code === 200) {
    dialogVisible.value = false;
    ElMessage({
      type: "success",
      message: "保存成功",
    });
    pageQuery(); //修改成功后重新获取数据
  } else {
    ElMessage({
      type: "error",
      message: res.message,
    });
  }
};
//校验图片地址
const validateLogoUrl = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请上传品牌图片"));
  } else {
    callback();
  }
};
//表单校验
const rules = {
  tmName: [{ required: true, message: "请输入品牌名称", trigger: "blur" }],
  //自定义logoUrl校验
  logoUrl: [{ required: true, validator: validateLogoUrl }],
};
</script>

<template>
  <div>
    <el-card>
      <!-- 添加品牌的按钮 -->
      <el-button type="primary" size="default" icon="Plus" @click="openDialog"
        >添加品牌</el-button
      >
      <!-- 表格展示 -->
      <el-table :data="tableData" style="margin: 10px 0" border>
        <!-- el-table-column默认使用div展示 -->
        <el-table-column type="index" label="序号" width="180" align="center" />
        <el-table-column
          prop="tmName"
          label="品牌名称"
          width="360"
          align="center"
        />
        <!-- el-table-column插槽展示 -->
        <el-table-column
          prop="logoUrl"
          label="品牌LOGO"
          width="360"
          align="center"
        >
          <!-- 展示图片 -->
          <template #default="{ row }">
            <img :src="row.logoUrl" alt="" style="width: 30px; height: 30px" />
          </template>
        </el-table-column>
        <!-- 更新时间 -->
        <el-table-column
          prop="updateTime"
          label="更新时间"
          width="360"
          align="center"
        />
        <!-- 品牌操作 -->
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <!-- 编辑 -->
            <el-button
              type="primary"
              size="small"
              icon="Edit"
              @click="handleEdit(row.id)"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="handleDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="paginationParam?.current"
        :page-size="paginationParam?.size"
        :page-sizes="[10, 15, 20]"
        :background="true"
        layout="prev, pager, next, jumper,->,total, sizes"
        :total="paginationParam?.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      title="品牌信息"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        :model="dialogData"
        style="width: 80%"
        :rules="rules"
        ref="dialogForm"
      >
        <el-form-item label="品牌名称：" label-width="140px" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="dialogData.tmName"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO：" label-width="140px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="dialogData.logoUrl"
              :src="dialogData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
          <el-button type="primary" @click="saveDialogData"> 保存 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
